<template>
  <a-card :bordered="false">
    <h3>挚友活动</h3>
    <LessFilter ref="filter" :type="3" @onAdd="handleAddOrEdit"  @onSearch="onSearch"></LessFilter>

    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="action" slot-scope="record">

        <a-button class="btn" style="min-width: 90px;" @click="handleAddOrEdit(record)">编辑</a-button>
        <a-popconfirm title="确定删除当前活动吗？" ok-text="确定" cancel-text="暂不" @confirm="handleDelete(record)">
          <a-button class="btn" style="min-width: 90px;">删除</a-button>
        </a-popconfirm>
      </span>
      <div slot="activityCoverImg" slot-scope="text"><img :src="text" alt="" srcset="" style="width: 50px" /></div>
      <div slot="activityCoverState" slot-scope="text,record"><a-switch :checked="text == 1 ? true : false"  checked-children="启用" un-checked-children="禁用"  @change="onChange(record,text)" /></div>
    </s-table>

    <a-modal :title="(edit ? '编辑' : '新增') + '挚友活动'" :visible="visible" width="800px" @ok="modelFormOk" @cancel="visible = false">
      <a-spin :spinning="spinning" tip="加载中...">
        <a-form-model ref="storeForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
          <a-form-model-item label="活动名称" prop="activityName">
            <a-input allowClear v-model.trim="form.activityName" :maxLength="16" placeholder="最多输入16字"/>
          </a-form-model-item>
          <a-form-model-item label="品牌" prop="brandId">
            <a-select
              placeholder="请选择品牌"
              v-model="form.brandId"
            >
              <a-select-option :value="item.id" v-for="item in brandList" :key="item.id">
                {{ item.brandName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="活动时间" prop="time">
            <a-range-picker
              style="width:100%;"
              show-time
              valueFormat="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="form.time"
            />
          </a-form-model-item>
          <a-form-model-item label="封面图片" prop="activityCoverImg">
            <span style="display: inline-block;vertical-align: top; width: 250px;">
              <JImageUpload
                :uploadParams="getUploadParams()"
                :isMove="false"
                :isMultiple="true"
                :fileSize="10"
                :number="1"
                :accept="'image/*'"
                @fileChange="fileConsumeImgeUrlChange"
                v-model="consumeImgeUrlList"
              ></JImageUpload>
            </span>
          </a-form-model-item>
          <a-form-item label="亲密值门槛" prop="closeValueType" >
            <a-radio-group v-model="form.closeValueType" >
              <a-radio :value="0">
                不限
              </a-radio>
              <a-radio :value="1">
                限制
              </a-radio>
            </a-radio-group>
            <a-input-number v-if="form.closeValueType == 1" id="inputNumber" v-model.trim="form.closeValueFloor" :min="0" :precision="0"/>
          </a-form-item>
          <a-form-item label="跳转链接" prop="linkType">
            <a-radio-group v-model="form.linkType">
              <a-radio :value="1">
                内链
              </a-radio>
              <a-radio :value="2">
                外链
              </a-radio>
            </a-radio-group>
            <span v-if="form.linkType == 1">
              <JImageUpload
                :uploadParams="getUploadParams()"
                :isMove="false"
                :isMultiple="true"
                :fileSize="10"
                :number="9"
                :accept="'image/*'"
                @fileChange="filelinkImgUrlChange"
                v-model="linkImgeUrlList"
              ></JImageUpload>
            </span>
          </a-form-item>
          <a-form-item label="活动详情链接" v-if="form.linkType == 2">
            <a-input placeholder="" v-model.trim="form.linkUrl" placeholder="请输入活动详情链接"/>
          </a-form-item>
          <a-form-item label="活动参与链接" v-if="form.linkType == 2">
            <a-input placeholder="" v-model.trim="form.activityLinkUrl" placeholder="请输入活动参与链接"/>
          </a-form-item>
          <a-form-model-item label="外链appID" v-if="form.linkType == 2">
            <a-input v-model.trim="form.appid" placeholder="请输入外链appID"/>
          </a-form-model-item>
          <a-form-model-item label="消息模版ID">
            <a-input v-model.trim="form.msgTemplateId" placeholder="请输入消息模版ID"/>
          </a-form-model-item>
          <a-form-model-item label="微信消息模版ID">
            <a-input v-model.trim="form.wxTemplateId" placeholder="请输入微信消息模版ID"/>
          </a-form-model-item>
          <a-form-model-item label="备注" prop="remark">
            <a-textarea v-model.trim="form.remark" :maxLength="ruleLimit" placeholder="" :rows="8" allowClear />
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>

  </a-card>
</template>
<script>
  import moment from 'moment'
  import { activityInfoList,brandList, saveOrUpdateActivity, activityDetail, removeActivity,onOrOffActivity } from '@/api/marketingCenter/less'
  import { STable } from '@/views/box/components'
  import LessFilter from '../components/lessFilter'
  import AFormModelItem from 'ant-design-vue/es/form-model/FormItem'
  import AFormItem from 'ant-design-vue/es/form/FormItem'
  import JImageUpload from '../../components/JImageUpload.vue'

  export default {
    components: {
      AFormItem,
      AFormModelItem,
      LessFilter,
      STable,
      JImageUpload,
    },
    data() {
      return {
        ruleLimit: 500,
        visible: false,
        edit: false,
        spinning: false,
        loading: false,
        imageUrl: '',
        consumeImgeUrlList: [],
        linkImgeUrlList: [],
        form: {
          id: 0,
          activityCoverImg: '',
          activityEndDate: '',
          activityName: '',
          activityStartDate: '',
          activityState: '',
          activityType: '',
          appid: '',
          brandId: '',
          closeValueType: '',
          closeValueFloor: '',
          couponList: [],
          time: [],
          linkType: '',
          linkUrl: '',
          activityLinkUrl: '',
          remark: '',
          msgTemplateId: '',
          wxTemplateId: '',
        },
        columns: [
          {
            title: '封面图',
            align: 'center',
            dataIndex: 'activityCoverImg',
            scopedSlots: { customRender: 'activityCoverImg' },
          },{
            title: '活动名称',
            align: 'center',
            dataIndex: 'activityName'
          },
          {
            title: '开始时间',
            dataIndex: 'activityStartDate',
            align:"center",
            customRender: (text) => {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          },{
            title: '结束时间',
            dataIndex: 'activityEndDate',
            align:"center",
            customRender: (text) => {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          },{
            title: '亲密值门槛',
            align: 'center',
            dataIndex: 'closeValueFloor'
          },{
            title: '品牌',
            align: 'center',
            dataIndex: 'brandName'
          },{
            title: '消息模板ID',
            align: 'center',
            dataIndex: 'msgTemplateId'
          },{
            title: '状态',
            align: 'center',
            dataIndex: 'activityState',
            scopedSlots: { customRender: 'activityCoverState' },

          },
          {
            title: '操作',
            width: '350px',
            align: 'center',
            fixed: 'right',
            scopedSlots: { customRender: 'action' }
          }
        ],
        paginationProps: {
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
          // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
        },
        brandList: [],


        queryParam: {
          time:[]
        },

        uploadData: {
        },
        rules: {
          activityName: [{ required: true, message: '请输入', trigger: 'blur' }],
          brandId: [{ required: true, message: '请选择', trigger: 'change' }],
          time: [{ required: true, message: '请选择', trigger: 'change' }],
          activityCoverImg: [{ required: true, message: '请选择', trigger: 'change' }],
        },

        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          if (this.requestFlag()) return
          const data = {
            "current": parameter.pageNo,
            "size": parameter.pageSize,
            activityType: 1,
            ...this.queryParam,
            "startDate":this.queryParam.startTime,
            "endDate":this.queryParam.endTime,
          }
          return activityInfoList(data).then(res => {

            if (res.code === 200) {
              const { records, total, size, current } = res.data
              const data = {
                page: {
                  count: total,
                  pageNo: current,
                  pageSize: size,
                  pages: Math.ceil(total / size)
                },
                data: records
              }
              return data
            } else {
              this.$message.error(res.msg || res.message)
              const data = {
                page: {
                  count: 0,
                  pageNo: 0,
                  pages: 0
                },
                data: []
              }
              return data
            }
          })
        }
      }
    },
    activated() {
    },
    computed: {},
    mounted() {
      this.getBrandList()
    },
    watch: {
    },
    methods: {
      requestFlag() {

        const currentPathBase = '/marketingCenter/less/activity/themeActivityList'
        const currentPath = this.$route.path
        if (!currentPath.includes(currentPathBase)) return true
        return false
      },

      // 删除
      handleDelete(record) {
        removeActivity({id: record.id}).then(res => {
          if (res.code === 200) {
            this.$refs.table.refresh()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },


      // 新增编辑
      handleAddOrEdit(v) {
        if(v != 'null'){
          activityDetail({id: v.id}).then(res => {
            if (res.code === 200) {
              this.form.id = res.data.id;
              this.consumeImgeUrlList = res.data.activityCoverImg ? res.data.activityCoverImg.split(',') : []
              this.form.activityEndDate = res.data.activityEndDate;
              this.form.activityName = res.data.activityName;
              this.form.activityStartDate = res.data.activityStartDate;
              this.form.activityState = res.data.activityState;
              this.form.appid = res.data.appid;
              this.form.brandId = res.data.brandId;
              this.form.brandName = res.data.brandName;
              this.form.closeValueFloor = res.data.closeValueFloor;
              this.form.closeValueType = res.data.closeValueType;
              this.form.couponList = res.data.couponList;
              this.form.linkType = res.data.linkType;
              this.form.msgTemplateId = res.data.msgTemplateId;
              this.form.wxTemplateId = res.data.wxTemplateId;
              this.form.remark = res.data.remark;
              this.visible = true;
              this.edit = true;
              if(this.form.linkType == 1){
                this.linkImgeUrlList = res.data.linkUrl ? res.data.linkUrl.split(',') : []
                this.form.linkUrl = "";
              }else{
                this.form.linkUrl = res.data.linkUrl;
              }
              this.form.activityLinkUrl = res.data.activityLinkUrl
              this.form.time = [res.data.activityStartDate,res.data.activityEndDate];

            } else {
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
          })
        }else{
          this.form.id = 0;
          this.edit = false;
          this.consumeImgeUrlList = [];
          this.form.activityEndDate = '';
          this.form.activityStartDate = '';
          this.form.activityName = '';
          this.form.brandId = '';
          this.form.appid = '';
          this.form.brandName = '';
          this.form.closeValueFloor = '';
          this.form.closeValueType = 0;
          this.form.couponList = [];
          this.form.linkType = 1;
          this.form.linkUrl = '';
          this.form.activityLinkUrl = '';
          this.form.msgTemplateId = '';
          this.form.wxTemplateId = '';
          this.form.remark = '';
          this.form.time = [];
          this.visible = true;
          this.linkImgeUrlList = []
        }
      },


      //查询
      onSearch(obj) {
        this.queryParam = obj
        this.$refs.table.refresh(true)
      },

      modelFormOk() {
        this.$refs.storeForm.validate(valid => {
          if (valid) {
            const data = {
              ...this.form,
              activityType:1,
              activityStartDate: this.form.time[0],
              activityEndDate: this.form.time[1],
              closeValueFloor: this.form.closeValueType == 0 ? 0 : this.form.closeValueFloor == "" ? 0 :this.form.closeValueFloor
            }
            this.spinning = true
            saveOrUpdateActivity(data).then(res => {
              if (res.code === 200) {
                this.spinning = false
                this.visible = false
                this.$refs.table.refresh(true)
              } else {
                this.spinning = false
                this.$message.error(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      // 获取品牌列表
      getBrandList() {
        brandList({
          current: 0,
          size: 99,
          state: 1
        }).then(res => {
          if (res.code === 200) {
            this.brandList = res.data.records
            console.log(this.brandList)
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
        })
      },
      //状态修改
      onChange(val,text){
        onOrOffActivity({id: val.id}).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg || res.message)
            this.$refs.table.refresh()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },
      // 图片上传

      getUploadParams() {
        return {
          actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
          headers: {
            authorization: 'authorization-text'
          },
          uploadHost: 'https://img.bzhz.jnbygroup.com/'
        }
      },

      // 图片change
      fileConsumeImgeUrlChange(list) {
        this.form.activityCoverImg = list.length ? list[0].url : ''
      },
      filelinkImgUrlChange(list) {
        let arr = new Array();
        if(list && list.length>0){
          list.forEach(item=>{
            arr.push(item.url)
          })
        }
        this.form.linkUrl = arr.toString();
      },
    }
  }
</script>
<style lang="less" scoped>
  /deep/ .ant-tabs-bar {
    margin-bottom: 0;
  }

  .img {
    display: block;
    margin: 0 auto;
    width: 120px;
    height: 120px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }
  .btn{
    margin: 4px;
  }
</style>
